<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>护士管理</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <link th:href="@{/css/admin.css}" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
<div class="content-section" th:fragment="content">
    <h2><i class="fas fa-user-nurse"></i> 护士管理</h2>
    
    <div class="filter-section">
        <select id="deptSelect" class="dept-select">
            <option value="">所有科室</option>
        </select>
    </div>

    <div class="action-bar">
        <button class="btn btn-primary" onclick="showAddNurseModal()">
            <i class="fas fa-plus"></i> 添加护士
        </button>
    </div>

    <div th:fragment="nurseList">
        <table class="data-table">
            <thead>
                <tr>
                    <th>工号</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>年龄</th>
                    <th>身份证号</th>
                    <th>电话</th>
                    <th>所属科室</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="nurseTableBody">
            </tbody>
        </table>
    </div>

    <div id="addNurseModal" class="modal" style="display: none;">
        <div class="modal-content">
            <h3>添加新护士</h3>
            <form id="addNurseForm">
                <div class="form-group">
                    <label for="nurseId">护士ID</label>
                    <input type="text" id="nurseId" name="nurseId" required>
                </div>
                
                <div class="form-group">
                    <label for="nurseName">姓名</label>
                    <input type="text" id="nurseName" name="nurseName" required>
                </div>
                
                <div class="form-group">
                    <label>性别</label>
                    <div class="radio-group">
                        <label>
                            <input type="radio" name="nurseGender" value="男" checked> 男
                        </label>
                        <label>
                            <input type="radio" name="nurseGender" value="女"> 女
                        </label>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="nurseAge">年龄</label>
                    <input type="number" id="nurseAge" name="nurseAge" min="0" required>
                </div>
                
                <div class="form-group">
                    <label for="nurseIdCard">身份证号</label>
                    <input type="text" id="nurseIdCard" name="nurseIdCard" required>
                </div>
                
                <div class="form-group">
                    <label for="nursePhone">电话号码</label>
                    <input type="tel" id="nursePhone" name="nursePhone" required>
                </div>
                
                <div class="form-group">
                    <label for="deptIdSelect">所属科室</label>
                    <select id="deptIdSelect" name="deptId" required>
                        <option value="">请选择科室</option>
                    </select>
                </div>
                
                <div class="form-buttons">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <button type="button" class="btn btn-secondary" onclick="hideAddNurseModal()">取消</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 添加病房分配信息模态框 -->
    <div id="wardAssignmentModal" class="modal" style="display: none;">
        <div class="modal-content">
            <h3>护士病房分配信息</h3>
            <div id="wardAssignmentList">
                <!-- 病房分配信息将在这里动态显示 -->
            </div>
            <div class="form-buttons">
                <button type="button" class="btn btn-secondary" onclick="hideWardAssignmentModal()">关闭</button>
            </div>
        </div>
    </div>

    <!-- 添加病房分配模态框 -->
    <div id="assignWardModal" class="modal" style="display: none;">
        <div class="modal-content">
            <h3>分配病房</h3>
            <form id="assignWardForm">
                <input type="hidden" id="assignNurseId">
                <div class="form-group">
                    <label for="floorSelect">选择楼层</label>
                    <select id="floorSelect" required>
                        <option value="">请选择楼层</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="wardSelect">选择病房</label>
                    <select id="wardSelect" required>
                        <option value="">请先选择楼层</option>
                    </select>
                </div>
                <div class="form-buttons">
                    <button type="submit" class="btn btn-primary">确认分配</button>
                    <button type="button" class="btn btn-secondary" onclick="hideAssignWardModal()">取消</button>
                </div>
            </form>
        </div>
    </div>

    <script th:inline="javascript">
    /*<![CDATA[*/
    // 在页面加载完成后初始化
    $(document).ready(function() {
        console.log('Document ready, initializing nurse management...');
        initializeNurseManage();
        
        // 绑定表单提交事件
        $('#addNurseForm').on('submit', function(e) {
            e.preventDefault();
            addNurseForm();
        });
    });
    
    // 页面初始化
    function initializeNurseManage() {
        console.log('Initializing nurse management page...');
        loadDepartments();
        loadNurses();
        
        // 绑定科室选择事件
        $('#deptSelect').on('change', function() {
            var selectedDeptId = $(this).val();
            console.log('Selected department ID:', selectedDeptId);
            if (selectedDeptId) {
                loadNursesByDepartment(selectedDeptId);
            } else {
                loadNurses();
            }
        });
    }

    // 加载科室列表
    function loadDepartments() {
        console.log('Loading departments...');
        $.ajax({
            url: /*[[@{/admin/departments}]]*/ '/admin/departments',
            method: 'GET',
            dataType: 'json',
            success: function(departments) {
                console.log('Received departments:', departments);
                var deptSelect = $('#deptSelect');
                deptSelect.find('option:not(:first)').remove();
                
                departments.forEach(function(dept) {
                    deptSelect.append($('<option>', {
                        value: dept.deptId,
                        text: dept.deptName
                    }));
                });
            },
            error: function(xhr, status, error) {
                console.error('Failed to load departments:', error);
                if (xhr.status === 401) {
                    window.location.href = /*[[@{/admin/auth/login}]]*/ '/admin/auth/login';
                } else {
                    alert('加载科室列表失败，请刷新页面重试');
                }
            }
        });
    }

    // 加载所有护士
    function loadNurses() {
        console.log('Loading all nurses...');
        $.ajax({
            url: /*[[@{/admin/nurses}]]*/ '/admin/nurses',
            method: 'GET',
            dataType: 'json',
            success: function(nurses) {
                console.log('Received nurses:', nurses);
                displayNurses(nurses);
            },
            error: function(xhr, status, error) {
                console.error('Failed to load nurses:', error);
                if (xhr.status === 401) {
                    window.location.href = /*[[@{/admin/auth/login}]]*/ '/admin/auth/login';
                } else {
                    var tbody = $('#nurseTableBody');
                    tbody.empty();
                    tbody.append('<tr><td colspan="8" class="text-center text-danger">加载护士列表失败，请刷新页面重试</td></tr>');
                }
            }
        });
    }

    // 根据科室加载护士
    function loadNursesByDepartment(deptId) {
        console.log('Loading nurses for department:', deptId);
        var url = /*[[@{/admin/nurses/department/}]]*/ '/admin/nurses/department/';
        url = url + deptId;  // 正确拼接URL
        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function(nurses) {
                console.log('Received nurses for department:', nurses);
                displayNurses(nurses);
            },
            error: function(xhr, status, error) {
                console.error('Failed to load nurses for department:', error);
                if (xhr.status === 401) {
                    window.location.href = /*[[@{/admin/auth/login}]]*/ '/admin/auth/login';
                } else {
                    var tbody = $('#nurseTableBody');
                    tbody.empty();
                    tbody.append('<tr><td colspan="8" class="text-center text-danger">加载护士列表失败，请刷新页面重试</td></tr>');
                }
            }
        });
    }

    // 显示护士数据
    function displayNurses(nurses) {
        var tbody = $('#nurseTableBody');
        tbody.empty();
        
        if (!nurses || nurses.length === 0) {
            tbody.append('<tr><td colspan="8" class="text-center">暂无护士数据</td></tr>');
            return;
        }
        
        nurses.forEach(function(nurse) {
            var row = $('<tr>');
            row.append($('<td>').text(nurse.nurseId || '-'));
            row.append($('<td>').text(nurse.nurseName || '-'));
            row.append($('<td>').text(nurse.nurseGender || '-'));
            row.append($('<td>').text(nurse.nurseAge || '-'));
            row.append($('<td>').text(nurse.nurseIdCard || '-'));
            row.append($('<td>').text(nurse.nursePhone || '-'));
            row.append($('<td>').text(nurse.department ? nurse.department.deptName : '-'));
            
            // 添加查看按钮
            var actionCell = $('<td>');
            var viewButton = $('<button>')
                .addClass('btn btn-info btn-sm')
                .html('<i class="fas fa-eye"></i> 查看分配')
                .on('click', function() {
                    showWardAssignments(nurse.nurseId);
                });
            actionCell.append(viewButton);
            row.append(actionCell);
            
            tbody.append(row);
        });
    }

    function showWardAssignments(nurseId) {
        var baseUrl = /*[[@{/admin/nurses/assignments/}]]*/ '/admin/nurses/assignments/';
        $.ajax({
            url: baseUrl + nurseId,
            method: 'GET',
            success: function(assignments) {
                var list = $('#wardAssignmentList');
                list.empty();
                
                if (assignments.length === 0) {
                    list.append('<p class="text-center">该护士暂未分配病房</p>');
                } else {
                    var table = $('<table>').addClass('data-table');
                    var thead = $('<thead>').append(
                        $('<tr>')
                            .append($('<th>').text('楼层'))
                            .append($('<th>').text('病房号'))
                            .append($('<th>').text('操作'))
                    );
                    var tbody = $('<tbody>');
                    
                    assignments.forEach(function(assignment) {
                        var cancelButton = $('<button>')
                            .addClass('btn btn-danger btn-sm')
                            .html('<i class="fas fa-times"></i> 取消分配')
                            .on('click', function() {
                                if (confirm('确定要取消该护士的这个病房分配吗？')) {
                                    cancelWardAssignment(nurseId, assignment.wardId);
                                }
                            });
                            
                        tbody.append(
                            $('<tr>')
                                .append($('<td>').text(assignment.floorNum + '楼'))
                                .append($('<td>').text(assignment.wardNum + '号房'))
                                .append($('<td>').append(cancelButton))
                        );
                    });
                    
                    table.append(thead).append(tbody);
                    list.append(table);
                }
                
                // 添加分配按钮
                var assignButton = $('<button>')
                    .addClass('btn btn-primary mt-3')
                    .html('<i class="fas fa-plus"></i> 分配新病房')
                    .on('click', function() {
                        showAssignWardModal(nurseId);
                    });
                list.append(assignButton);
                
                $('#wardAssignmentModal').show();
            },
            error: function(xhr, status, error) {
                console.error('获取病房分配信息失败:', {
                    status: status,
                    error: error,
                    response: xhr.responseText
                });
                alert('获取病房分配信息失败：' + error);
            }
        });
    }

    function cancelWardAssignment(nurseId, wardId) {
        $.ajax({
            url: /*[[@{/admin/nurses/assignments/cancel}]]*/ '/admin/nurses/assignments/cancel',
            method: 'POST',
            data: {
                nurseId: nurseId,
                wardId: wardId
            },
            success: function(response) {
                if (response.success) {
                    alert('取消分配成功');
                    // 重新加载该护士的病房分配信息
                    showWardAssignments(nurseId);
                } else {
                    alert(response.message || '取消分配失败');
                }
            },
            error: function(xhr, status, error) {
                console.error('取消分配失败:', {
                    status: status,
                    error: error,
                    response: xhr.responseText
                });
                alert('取消分配失败：' + error);
            }
        });
    }

    function hideWardAssignmentModal() {
        $('#wardAssignmentModal').hide();
    }

    function showAddNurseModal() {
        $('#addNurseModal').show();
        loadDepartmentsForSelect();
    }

    function hideAddNurseModal() {
        $('#addNurseModal').hide();
        $('#addNurseForm')[0].reset();
    }

    // 处理表单提交
    function addNurseForm() {
        // 获取表单数据
        var formData = {
            nurseId: $('#nurseId').val(),
            nurseName: $('#nurseName').val(),
            nurseGender: $('input[name="nurseGender"]:checked').val(),
            nurseAge: parseInt($('#nurseAge').val()),
            nurseIdCard: $('#nurseIdCard').val(),
            nursePhone: $('#nursePhone').val(),
            deptId: parseInt($('#deptIdSelect').val())
        };

        // 表单验证
        var errors = [];
        
        // 验证护士ID
        if (!formData.nurseId) {
            errors.push('护士ID不能为空');
        } else if (!/^[A-Za-z][A-Za-z0-9]*$/.test(formData.nurseId)) {
            errors.push('护士ID必须以字母开头，且只能包含字母和数字');
        }
        
        // 验证姓名
        if (!formData.nurseName) {
            errors.push('护士姓名不能为空');
        } else if (formData.nurseName.length > 50) {
            errors.push('护士姓名长度不能超过50个字符');
        }
        
        // 验证性别
        if (!formData.nurseGender) {
            errors.push('请选择性别');
        }
        
        // 验证年龄
        if (!formData.nurseAge) {
            errors.push('年龄不能为空');
        } else if (formData.nurseAge < 18 || formData.nurseAge > 100) {
            errors.push('年龄必须在18-100岁之间');
        }
        
        // 验证身份证号
        if (!formData.nurseIdCard) {
            errors.push('身份证号不能为空');
        } else if (!/^\d{17}[\dX]$/.test(formData.nurseIdCard)) {
            errors.push('请输入正确的18位身份证号');
        }
        
        // 验证电话号码
        if (!formData.nursePhone) {
            errors.push('电话号码不能为空');
        } else if (!/^\d{11}$/.test(formData.nursePhone)) {
            errors.push('请输入正确的11位手机号码');
        }
        
        // 验证科室
        if (!formData.deptId) {
            errors.push('请选择科室');
        }
        
        // 如果有错误，显示错误信息并返回
        if (errors.length > 0) {
            alert(errors.join('\n'));
            return;
        }

        // 发送请求
        $.ajax({
            url: /*[[@{/admin/addNurse}]]*/ '',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                if (response.success) {
                    alert('添加成功，护士ID：' + response.nurseId + '\n');
                    hideAddNurseModal();
                    loadNurses(); // 刷新护士列表
                } else {
                    alert(response.message || '添加失败');
                }
            },
            error: function(xhr, status, error) {
                console.error('Failed to add nurse:', xhr.responseText);
                var errorMessage = '添加失败';
                
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    }
                } catch(e) {
                    // 处理特定的错误信息
                    if (xhr.responseText.includes('nurseIdCard')) {
                        errorMessage = '该身份证号已被注册';
                    } else if (xhr.responseText.includes('nursePhone')) {
                        errorMessage = '该电话号码已被注册';
                    } else if (xhr.responseText.includes('nurseId')) {
                        errorMessage = '该护士ID已存在';
                    }
                }
                
                alert(errorMessage);
            }
        });
    }

    function showAssignWardModal(nurseId) {
        $('#wardAssignmentModal').hide();
        $('#assignNurseId').val(nurseId);
        loadFloors(nurseId);
        $('#assignWardModal').show();
    }

    function hideAssignWardModal() {
        $('#assignWardModal').hide();
        $('#wardAssignmentModal').show();
    }

    function loadFloors(nurseId) {
        var url = /*[[@{/admin/nurses/}]]*/ '/admin/nurses/';
        $.ajax({
            url: url + nurseId + '/department/floors',
            method: 'GET',
            success: function(floors) {
                var select = $('#floorSelect');
                select.empty();
                select.append($('<option>', {
                    value: '',
                    text: '请选择楼层'
                }));
                
                floors.forEach(function(floor) {
                    select.append($('<option>', {
                        value: floor,
                        text: floor + '楼'
                    }));
                });
            },
            error: function(xhr, status, error) {
                console.error('加载楼层失败:', error);
                alert('加载楼层失败：' + error);
            }
        });
    }

    function loadWards(nurseId, floorNum) {
        var url = /*[[@{/admin/nurses/}]]*/ '/admin/nurses/';
        $.ajax({
            url: url + nurseId + '/department/floors/' + floorNum + '/wards',
            method: 'GET',
            success: function(wards) {
                var select = $('#wardSelect');
                select.empty();
                select.append($('<option>', {
                    value: '',
                    text: '请选择病房'
                }));
                
                wards.forEach(function(ward) {
                    select.append($('<option>', {
                        value: ward.wardId,
                        text: ward.wardNum + '号房'
                    }));
                });
            },
            error: function(xhr, status, error) {
                console.error('加载病房失败:', error);
                alert('加载病房失败：' + error);
            }
        });
    }

    // 绑定楼层选择事件
    $('#floorSelect').on('change', function() {
        var floorNum = $(this).val();
        var nurseId = $('#assignNurseId').val();
        
        if (floorNum) {
            loadWards(nurseId, floorNum);
        } else {
            $('#wardSelect').empty().append($('<option>', {
                value: '',
                text: '请先选择楼层'
            }));
        }
    });

    // 绑定分配表单提交事件
    $('#assignWardForm').on('submit', function(e) {
        e.preventDefault();
        
        var nurseId = $('#assignNurseId').val();
        var wardId = $('#wardSelect').val();
        
        if (!wardId) {
            alert('请选择要分配的病房');
            return;
        }
        
        $.ajax({
            url: /*[[@{/admin/nurses/assignments/assign}]]*/ '/admin/nurses/assignments/assign',
            method: 'POST',
            data: {
                nurseId: nurseId,
                wardId: wardId
            },
            success: function(response) {
                if (response.success) {
                    alert('分配成功');
                    hideAssignWardModal();
                    showWardAssignments(nurseId);
                } else {
                    alert(response.message || '分配失败');
                }
            },
            error: function(xhr, status, error) {
                console.error('分配失败:', {
                    status: status,
                    error: error,
                    response: xhr.responseText
                });
                alert('分配失败：' + error);
            }
        });
    });

    /*]]>*/
    </script>

    <style th:fragment="style">
    /* 表格样式 */
    .data-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }

    .data-table th,
    .data-table td {
        padding: 12px;
        text-align: left;
        border-bottom: 1px solid #e0e0e0;
    }

    .data-table th {
        background-color: #f5f5f5;
        font-weight: 600;
    }

    .data-table tr:hover {
        background-color: #f8f9fa;
    }

    /* 下拉列表样式 */
    select {
        width: 200px;
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        background-color: white;
        font-size: 14px;
        cursor: pointer;
        appearance: none;
        -webkit-appearance: none;
        -moz-appearance: none;
        background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
        background-repeat: no-repeat;
        background-position: right 8px center;
        background-size: 16px;
        padding-right: 32px;
    }

    select:hover {
        border-color: #aaa;
    }

    select:focus {
        border-color: #4CAF50;
        outline: none;
        box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
    }

    /* 过滤器样式 */
    .filter-section {
        margin-bottom: 20px;
    }

    .dept-select {
        width: 200px;
    }

    /* 文本对齐 */
    .text-center {
        text-align: center;
    }

    .text-danger {
        color: #dc3545;
    }

    /* 按钮样式 */
    .action-bar {
        margin-bottom: 20px;
    }

    .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }

    .btn-primary {
        background-color: #4CAF50;
        color: white;
    }

    .btn-primary:hover {
        background-color: #45a049;
    }

    .btn-secondary {
        background-color: #f44336;
        color: white;
    }

    .btn-secondary:hover {
        background-color: #d32f2f;
    }

    /* 模态框样式 */
    .modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    }

    .modal-content {
        background-color: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        max-width: 500px;
        width: 100%;
    }

    .modal-content h3 {
        margin-top: 0;
        margin-bottom: 20px;
    }

    /* 表单样式 */
    .form-group {
        margin-bottom: 15px;
    }

    .form-group label {
        display: block;
        margin-bottom: 5px;
        font-weight: 500;
    }

    .form-group input,
    .form-group select {
        width: 100%;
        max-width: 100%;
    }

    .form-buttons {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        margin-top: 20px;
    }

    /* 添加模态框样式 */
    .modal-content table {
        width: 100%;
        margin-top: 20px;
        margin-bottom: 20px;
    }

    .btn-info {
        background-color: #17a2b8;
        color: white;
        margin-right: 5px;
    }

    .btn-info:hover {
        background-color: #138496;
    }

    .btn-sm {
        padding: 4px 8px;
        font-size: 12px;
    }

    .btn-danger {
        background-color: #dc3545;
        color: white;
    }

    .btn-danger:hover {
        background-color: #c82333;
    }

    .mt-3 {
        margin-top: 1rem;
    }
    </style>
</div>
</body>
</html> 